//
//  MovieViewController.m
//  豆瓣HW
//
//  Created by dllo on 15/11/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MovieViewController.h"
#import "MovieTableViewCell.h"
#import "DetailMovieViewController.h"
#import "Movie.h"
#import "MovieTwoViewController.h"

@interface MovieViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) NSMutableArray *movieArr;
@property (nonatomic, retain) NSMutableArray *countArr;

@end

@implementation MovieViewController

- (void)dealloc
{
    [_tableV release];
    [_movieArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"电影";
    self.navigationController.navigationBar.translucent = YES;
    
    [self getData];
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
    UIImage *rightImage = [UIImage imageNamed:@"btn_nav_collection@2x.png"];
    rightImage = [rightImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    

    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightImage style:UIBarButtonItemStylePlain target:self action:@selector(barAction:)];
    
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    while (self.movieArr.count == 0) {
//        [self.tableV reloadData];
//    }
//}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [self.tableV reloadData];
//}


- (void)getData
{
    
    NSURL *url = [NSURL URLWithString:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php"];
    
    // 3, 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 1, 创建对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    // 2,请求任务
    NSURLSessionDataTask *getTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.movieArr = [NSMutableArray array];
        NSMutableArray *arr = [dic objectForKey:@"result"];
        for (NSMutableDictionary *tempDic in arr) {
            
            Movie *mov = [[Movie alloc] init];
            mov.movieId = [tempDic objectForKey:@"movieId"];
 
            
            /*************************详情界面信息*********************/
            NSString *string1 = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/searchmovie.php?movieId=";
            
            NSString *detailConnector = [string1 stringByAppendingString: mov.movieId];
            
            NSURL *detailUrl = [NSURL URLWithString:detailConnector];
            
            NSURLRequest *detailRequest = [NSURLRequest requestWithURL:detailUrl];
            
            NSURLSession *detailSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            
            NSURLSessionDataTask *getDetailTask = [detailSession dataTaskWithRequest:detailRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                
                NSDictionary *detailDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableDictionary *detailTempDic = [detailDic objectForKey:@"result"];
                
                Movie *detailMovie = [[Movie alloc] init];
                [detailMovie setValuesForKeysWithDictionary:detailTempDic];
                
                /*************************图片*********************/
                NSURL *url = [NSURL URLWithString:detailMovie.poster];
                
                NSURLSession *session = [NSURLSession sharedSession];
                NSURLSessionDownloadTask *downImageT = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                    
                    NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    
                    NSString *file = [cach stringByAppendingPathComponent:detailMovie.movieid];
                    
                    NSFileManager *fileM = [NSFileManager defaultManager];
                    
                    [fileM moveItemAtPath:location.path toPath:file error:nil];
                    
                    detailMovie.image = [UIImage imageWithContentsOfFile:file];
                    
                }];
                
                [downImageT resume];
                /*************************图片*********************/

                
                [self.movieArr addObject:detailMovie];

                [mov release];
                [detailMovie release];
                
            }];
            [self.tableV reloadData];
            
            [getDetailTask resume];
            
        }
        [self.tableV reloadData];
        
    }];
    [getTask resume];
    
    
}

- (void)barAction:(UIBarButtonItem *)sender
{
    MovieTwoViewController *movieTwoVC = [[MovieTwoViewController alloc] init];
    
    movieTwoVC.array = self.movieArr;
    movieTwoVC.navigationItem.hidesBackButton = YES;
    [self.navigationController pushViewController:movieTwoVC animated:YES];
    [movieTwoVC release];
    
}

// 选中行操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailMovieViewController *detailMovieVC = [[DetailMovieViewController alloc] init];
    
    detailMovieVC.mov = [self.movieArr objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:detailMovieVC animated:YES];
    [detailMovieVC release];
    
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 4;
}
// 每个区有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 26;

}

// 铺建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (nil == cell) {
        cell = [[[MovieTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr] autorelease];
    }
    Movie *mov = [self.movieArr objectAtIndex:indexPath.row];
    cell.imageV2.image = mov.image;
    cell.label.text = mov.title;
    
    
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end
